package com.core.springSecurity.filter;

import com.common.utils.Constants;
import com.common.ErrorCodeEnum;
import com.common.config.Config;
import com.common.exception.BusinessException;
import com.common.utils.StringUtils;
import com.core.springSecurity.common.FingerprintUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: zql
 * @Description: 获取设备唯一ID
 * @Data: 14:45 2021/7/13
 */
@Slf4j
@Component
public class FingerprintFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        try {
            //获取唯一id
            String configFing = Config.getFingerprint();
            String fingerprint = httpServletRequest.getHeader(configFing);
            if (StringUtils.isNull(fingerprint)) {
                fingerprint = Constants.DEFAULT_FINGERPRINT;
            }
            if (!fingerprint.endsWith(Constants.FINGERPRINT_PREFIX) || fingerprint.length() != Constants.FINGERPRINT_LENGTH) {
                throw new BusinessException(ErrorCodeEnum.FINGERPRINT_FORMAT_FAILED);
            }

            FingerprintUtils.setFingerprintDeviceID(fingerprint);
        } catch (BusinessException e) {
            e.printStackTrace();
            log.error("获取指纹id失败 code:{},msg:{}",e.getErrorCodeEnum().getErrorCode(),e.getErrorCodeEnum().getErrorMsg());
            throw e;
        }catch (Exception e){
            e.printStackTrace();
            log.error("获取指纹id失败 且异常未被捕获");
            throw e;
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
